<?php
namespace app\Controller;
use app\BaseController;

use think\App;
use think\Controller;
use think\facade\Db;
use think\facade\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class ProductFeature extends BaseController
{

    // 新增产品特征
    public function create()
    {
        $name = Request::post('name');
        $sort = Request::post('sort', 0);
        if (empty($name)) {
            return json([
                'code' => 1,
                'msg' => '名称为必填字段'
            ]);
        }
        try {
            $data = [
                'name' => $name,
                'image' => '',
                'sort' => $sort,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            $id = Db::table('game_feature')->insertGetId($data);
            $feature = Db::table('game_feature')->find($id);
            return json([
                'code' => 0,
                'msg' => '新增成功',
                'data' => $feature
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '新增失败: ' . $e->getMessage()
            ]);
        }
    }

    // 获取产品特征详情
    public function detail($id)
    {
        $id = Request::get('id');
        $feature = Db::table('game_feature')->find($id);
        if (!$feature) {
            return json([
                'code' => 1,
                'msg' => '记录不存在'
            ]);
        }
        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => $feature
        ]);
    }

    // 编辑产品特征
    public function update($id)
    {
        $id = Request::post('id');
        $name = Request::post('name');
        $sort = Request::post('sort', 0);
        if (empty($name)) {
            return json([
                'code' => 1,
                'msg' => '名称为必填字段'
            ]);
        }
        $feature = Db::table('game_feature')->find($id);
        if (!$feature) {
            return json([
                'code' => 1,
                'msg' => '记录不存在'
            ]);
        }
        try {
            $data = [
                'name' => $name,
                //'feature_name' => $name,
                'sort' => $sort,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            Db::table('game_feature')->where('id', $id)->update($data);
            $updatedFeature = Db::table('game_feature')->find($id);
            return json([
                'code' => 0,
                'msg' => '编辑成功',
                'data' => $updatedFeature
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '编辑失败: ' . $e->getMessage()
            ]);
        }
    }

    public function delete($id)
    {
        // 输出传入的id
        error_log("传入的id: " . $id);
        $feature = Db::table('game_feature')->find($id);
        if (!$feature) {
            return json([
                'code' => 1,
                'msg' => '记录不存在'
            ]);
        }
        try {
            Db::table('game_feature')->where('id', $id)->delete();
            return json([
                'code' => 0,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '删除失败: ' . $e->getMessage()
            ]);
        }
    }

    // 产品特征列表
    public function list()
    {
        $featureId = Request::get('id');
        $featureName = Request::get('name');
        $page = Request::get('page', 1);
        $limit = Request::get('limit', 10);

        $query = Db::table('game_feature')
            ->field([
                'id AS id_str',  // 将id转换为字符串
                'name',
                'sort',
                'updated_at',
                'CAST(id AS CHAR) AS id' // 或直接在SQL层转换
            ]);

        if ($featureId) {
            $query->where(Db::raw('CAST(id AS CHAR)'), '=', $featureId);
        }
        if ($featureName) {
            $query->where('name', 'like', "%$featureName%");
        }

        $list = $query->order('sort', 'asc')
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ]);

        // 转换数据类型
        $list->each(function ($item) {
            if (is_array($item)) {
                $item['id'] = (string)$item['id'];
            } else {
                $item->id = (string)$item->id;
            }
            return $item;
        });

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => $list
        ]);
    }

    // 导入产品特征
    public function import()
    {
        $file = Request::file('file');
        if (!$file) {
            return json([
                'code' => 1,
                'msg' => '请上传文件'
            ]);
        }
        try {
            $inputFileName = $file->getPathname();
            $spreadsheet = IOFactory::load($inputFileName);
            $sheet = $spreadsheet->getActiveSheet();
            $highestRow = $sheet->getHighestRow();

            for ($row = 2; $row <= $highestRow; $row++) {
                $name = $sheet->getCell('A' . $row)->getValue();
                $sort = $sheet->getCell('B' . $row)->getValue();
                if ($name) {
                    $data = [
                        'name' => $name,
                        'feature_name' => $name,
                        'image' => '',
                        'sort' => $sort,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    Db::table('game_feature')->insert($data);
                }
            }
            return json([
                'code' => 0,
                'msg' => '导入成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '导入失败: ' . $e->getMessage()
            ]);
        }
    }

    // 导出产品特征
    public function export()
    {
        $featureId = Request::get('feature_id');
        $featureName = Request::get('feature_name');

        $query = Db::table('game_feature')
            ->field('id, feature_name, sort, updated_at');

        if ($featureId) {
            $query->where('id', $featureId);
        }
        if ($featureName) {
            $query->where('feature_name', 'like', "%$featureName%");
        }

        $list = $query->order('sort', 'asc')->select();

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '名称');
        $sheet->setCellValue('C1', '排序');
        $sheet->setCellValue('D1', '修改时间');

        $row = 2;
        foreach ($list as $item) {
            $sheet->setCellValue('A' . $row, $item['id']);
            $sheet->setCellValue('B' . $row, $item['feature_name']);
            $sheet->setCellValue('C' . $row, $item['sort']);
            $sheet->setCellValue('D' . $row, $item['updated_at']);
            $row++;
        }

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="product_features.xlsx"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }
}    